package com.hps.demo.service.impl;

import com.google.common.collect.Lists;
import com.hps.demo.entity.User;
import com.hps.demo.mapper.UserMapper;
import com.hps.demo.msg.KafkaSender;
import com.hps.demo.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author heps
 * @since 2020-10-27
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

  @Resource
  private KafkaSender kafkaSender;

  @Async("bizExecutor")
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void initData(Integer count) {
    log.info("start init user: {}", count);
//    List<User> userList = new ArrayList<>();
    Random random = new Random(System.currentTimeMillis());
    for (int i = 0; i < count; i++) {
      User user = new User();
      user.setName("user:" + RandomStringUtils.randomAlphanumeric(10));
      user.setAge(10 + random.nextInt(60));

      kafkaSender.send("userTopic", user);
//      userList.add(user);
//
//      if (userList.size() % 500 == 0) {
//        super.saveBatch(userList);
//        userList.clear();
//      }
    }

//    if (userList.size() > 0) {
//      super.saveBatch(userList);
//    }
    log.info("init user success");
  }

  @Cacheable(cacheNames = "user", key = "'id:' + #id")
  @Override
  public User getByIdCache(Long id) {
    return super.getById(id);
  }

  @Override
  public List<User> getNoOrderUser() {
    return baseMapper.getNoOrderUser();
  }
}
